package com.hlwxy.ssm.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenSingleton {

    static String APP_KEY = "dingtbgytedy1docdrjl";

    static String APP_SECRET = "1rAnIhDzBTJ0UEMqGC6cLFrHcp2i65fh8SufRSUW10ZCuh63KVSz2FdB7Pnxn7Io";

    private static Map<String, String> map = new HashMap<String, String>();

    public static String getToken() {
        String time = map.get("time");
        String accessToken = map.get("access_token");
        Long nowDate = new Date().getTime();

        if (accessToken != null && time != null && nowDate - Long.parseLong(time) < 3000 * 1000) {
            //System.out.println("accessToken存在，且没有超时 ， 返回单例");
            return accessToken;
        } else {
            //System.out.println("accessToken 超时 ， 或者不存在 ， 重新获取");

            //"这里是直接调用微信的API去直接获取 accessToken 和Jsapi_ticket 获取";
            String access_token = getAccessToken();
            //"获取jsapi_token";
            map.put("time", nowDate + "");
            map.put("access_token", access_token);

            accessToken = access_token;
        }

        return accessToken;
    }


    public static String getAccessToken() {
        String accessToken = null;
        DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey(APP_KEY);
        request.setAppsecret(APP_SECRET);
        request.setHttpMethod("GET");
        try {
            OapiGettokenResponse response = client.execute(request);
            JSONObject token= JSON.parseObject(response.getBody());
            accessToken=token.getString("access_token");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }
}
